// pages/index/index.js
const app = getApp();
const { generateQRCode, isValidColor, isValidText, isValidSize } = require('../../utils/qrcode');

Component({
  lifetimes: {
    attached() {
      // 获取状态栏高度
      const systemInfo = wx.getSystemInfoSync();
      const statusBarHeight = systemInfo.statusBarHeight || 20;

      this.setData({
        statusBarHeight: statusBarHeight,
        navBarHeight: statusBarHeight + 44 // 44是导航栏的高度
      });
    }
  },
  data: {
    qrContent: '', // 二维码内容
    qrSize: 300, // 默认尺寸
    qrErrorLevel: 'H', // 默认容错级别
    qrFgColor: '#000000', // 默认前景色
    qrBgColor: '#ffffff', // 默认背景色
    qrImagePath: '', // 生成的二维码图片路径
    debounceTimer: null,
  },
  methods: {
    // 跳转到历史记录页面
    goToHistory() {
      wx.navigateTo({
        url: '../history/history',
      })
    },

    // 二维码文本输入处理
    onContentInput(e) {
      const text = e.detail.value;
      if (!isValidText(text)) {
        wx.showToast({
          title: '内容不能超过500字符',
          icon: 'none'
        });
        return;
      }

      this.setData({ qrContent: text });
      this.generateQRCode();
    },

    // 尺寸变化处理
    onSizeChange(e) {
      const size = e.detail.value;
      if (!isValidSize(size)) {
        wx.showToast({
          title: '尺寸必须在100-1000之间',
          icon: 'none'
        });
        return;
      }
      this.setData({ qrSize: size }, () => {
        this.generateQRCode();
      });
    },

    // 容错级别变化处理
    onErrorLevelChange(e) {
      const level = e.currentTarget.dataset.level;
      this.setData({ qrErrorLevel: level }, () => {
        this.generateQRCode();
      });
    },

    // 前景色选择
    onForegroundColorTap() {
      wx.showModal({
        title: '设置前景色',
        content: '请输入十六进制颜色值（如 #000000）',
        editable: true,
        placeholderText: this.data.qrFgColor,
        success: (res) => {
          if (res.confirm && res.content) {
            if (isValidColor(res.content)) {
              this.setData({ qrFgColor: res.content }, () => {
                this.generateQRCode();
              });
            } else {
              wx.showToast({
                title: '颜色格式不正确',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    // 背景色选择
    onBackgroundColorTap() {
      wx.showModal({
        title: '设置背景色',
        content: '请输入十六进制颜色值（如 #FFFFFF）',
        editable: true,
        placeholderText: this.data.qrBgColor,
        success: (res) => {
          if (res.confirm && res.content) {
            if (isValidColor(res.content)) {
              this.setData({ qrBgColor: res.content }, () => {
                this.generateQRCode();
              });
            } else {
              wx.showToast({
                title: '颜色格式不正确',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    // 生成二维码
    async generateQRCode() {
      if (!this.data.qrContent) return;

      wx.showLoading({ title: '生成中...' });

      try {
        const imagePath = await generateQRCode({
          text: this.data.qrContent,
          width: this.data.qrSize,
          height: this.data.qrSize,
          colorDark: this.data.qrFgColor,
          colorLight: this.data.qrBgColor,
          correctLevel: this.data.qrErrorLevel,
          quietZone: 10
        });

        this.setData({ qrImagePath: imagePath });
        wx.hideLoading();
      } catch (e) {
        console.error('生成二维码失败:', e);
        wx.hideLoading();
        wx.showToast({
          title: '生成二维码失败',
          icon: 'none'
        });
      }
    },

    // 保存到相册
    saveToAlbum() {
      if (!this.data.qrImagePath) {
        wx.showToast({
          title: '请先生成二维码',
          icon: 'none'
        });
        return;
      }

      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                this.saveImageToAlbum();
              },
              fail: () => {
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存到相册的权限',
                  confirmText: '去授权',
                  cancelText: '取消',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting();
                    }
                  }
                });
              }
            });
          } else {
            this.saveImageToAlbum();
          }
        }
      });
    },

    // 保存图片到相册
    saveImageToAlbum() {
      wx.saveImageToPhotosAlbum({
        filePath: this.data.qrImagePath,
        success: () => {
          wx.showToast({ title: '保存成功' });
          this.saveToHistory();
        },
        fail: () => {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      });
    },

    // 保存到历史记录
    saveToHistory() {
      const history = wx.getStorageSync('qrHistory') || [];
      const newRecord = {
        content: this.data.qrContent,
        size: this.data.qrSize,
        errorLevel: this.data.qrErrorLevel,
        fgColor: this.data.qrFgColor,
        bgColor: this.data.qrBgColor,
        imagePath: this.data.qrImagePath,
        timestamp: Date.now()
      };

      history.unshift(newRecord);
      if (history.length > 10) {
        history.pop();
      }

      wx.setStorageSync('qrHistory', history);
    },

    // 分享
    onShareAppMessage() {
      return {
        title: '二维码生成器',
        path: '/pages/index/index',
        imageUrl: this.data.qrImagePath || ''
      };
    }
  }
});